﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Koala.Pro.Common;
using Koala.Pro.Core.Dto;
using Koala.Pro.Core.Models;
using Koala.Pro.Helpers;
using Koala.Pro.Services;

namespace Koala.Pro.ViewModels
{
    public partial class MenuListViewModel : BaseListViewModel<MenuInfo, string, MenuPagedDto>
    {
        [ObservableProperty]
        private TreeViewModel<CustomTreeNode> menuTreeModel = new TreeViewModel<CustomTreeNode>();


        public MenuListViewModel(IMenuService service)
            : base(service)
        {
            ExportFields = "Name,Icon,Seq,FunctionId,Visible,Expand,Tag,WpfType";
        }

        [RelayCommand]
        private async Task GetTree()
        {
            string typeId = App.ViewModel.SystemType;
            SystemTypeInfo systemTypeInfo = await BLLFactory<ISystemTypeService>.Instance.GetAsync(typeId);
            if (systemTypeInfo != null)
            {
                CustomTreeNode topNode = new CustomTreeNode
                {
                    Name = systemTypeInfo.Name,
                    IsChecked = true,
                    Icon = "Home24"
                };
                new List<MenuInfo>();
                List<MenuInfo> children = ((!App.ViewModel.IsSuperAdmin) ? (await BLLFactory<IMenuService>.Instance.GetMenuNodesByUser(App.ViewModel.UserInfo.Id, typeId)) : (await BLLFactory<IMenuService>.Instance.GetTree(systemTypeInfo.Id)));
                List<CustomTreeNode> list = AddMenuRecursive(children, topNode);
                MenuTreeModel.TreeItems = list;
                MenuTreeModel.FilteredTreeItems = new List<CustomTreeNode>(list);
            }
            NotifyChanged("MenuTreeModel");
        }

        private List<CustomTreeNode> AddMenuRecursive(List<MenuInfo> children, CustomTreeNode parentNode = null)
        {
            List<CustomTreeNode> list = new List<CustomTreeNode>();
            foreach (MenuInfo child in children)
            {
                CustomTreeNode customTreeNode = new CustomTreeNode
                {
                    Name = child.Name,
                    Id = child.Id,
                    Icon = child.Icon
                };
                AddMenuRecursive(child.Children, customTreeNode);
                list.Add(customTreeNode);
            }
            if (parentNode != null)
            {
                parentNode.Children = list;
                return new List<CustomTreeNode> { parentNode };
            }
            return list;
        }
    }
}
